<!-- 
  DatePicker 日期选择组件                 zls-2022/08/01
    所有属性、事件、方法、插槽，请参考      https://vant-contrib.gitee.io/vant/#/zh-CN/date-picker
    根据columns-type'属性，支持：年-月-日、年-月、月-日、年、月、日等类型

  Demo
    <Form ref="formRef">
      <z-date v-model="form.date1" label="开始日期" @confirm="confirmDate1"></z-date>
      <z-date v-model="form.date2" label="结束日期" @confirm="confirmDate2"></z-date>
    </Form>

    const form = reactive({
      date1: '',
      date2: '2023-08-01',
    })

    // 日期选择配置
    function confirmDate1(data) {
      if ($day(data).valueOf() > $day(form.date2).valueOf()) {
        showToast('开始日期不能大于结束日期')
        form.date1 = ''
        return
      }
    }
    function confirmDate2(data) {
      if ($day(data).valueOf() < $day(form.date1).valueOf()) {
        showToast('结束日期不能小于开始日期')
        form.date2 = ''
        return
      }
    }
 -->
<template>
  <z-input
    v-bind="{ ...attrsFieldDefault, ...$attrs, modelValue: inputVal }"
    :rules="$attrs['required'] || $attrs['required'] === '' ? [{ required: true, message: '请选择' }] : []"
    @click="show = true"
  >
    <template #right-icon>
      <z-svg name="chahao" v-if="inputVal" @click.stop="clear"></z-svg>
    </template>
  </z-input>
  <Popup v-model:show="show" v-bind="{ ...attrsPopupDefault, ...$attrs }" @click-overlay="show = false" @click-close-icon="show = false">
    <DatePicker v-bind="{ ...attrsDatePickerDefault, ...$attrs }" v-model="currentDate" @confirm="confirm" @cancel="show = false" />
  </Popup>
</template>

<script>
export default { name: 'z-date' }
</script>
<script setup>
import { ref, useAttrs, watch } from 'vue'
import { Popup, DatePicker } from 'vant'

import $day from 'dayjs'
const emit = defineEmits(['update:modelValue', 'clear', 'confirm'])
const attrs = useAttrs()

const inputVal = ref('')
const show = ref(false) // 是否显示弹框
const currentDate = ref([]) // 当前日期

// Field输入框默认属性
const attrsFieldDefault = {
  readonly: true,
  placeholder: '请选择',
  'is-link': true,
  maxlength: '2000'
}
// Popup弹框默认属性
const attrsPopupDefault = {
  position: 'bottom',
  round: true
}
// DatePicker默认属性
const attrsDatePickerDefault = {
  title: '日期选择',
  'columns-type': ['year', 'month', 'day'],
  'min-date': new Date($day().subtract(10, 'year')),
  'max-date': new Date($day().add(100, 'year')),
  formatter: (type, option) => {
    const obj = { year: '年', month: '月', day: '日' }
    Object.entries(obj).forEach(([key, value]) => {
      if (type === key) {
        option.text += value
      }
    })
    return option
  }
}

// 格式化时间
const formatTimeObj = {
  'year-month-day': 'YYYY-MM-DD',
  'year-month': 'YYYY-MM',
  'month-day': 'MM-DD',
  year: 'YYYY',
  month: 'MM',
  day: 'DD'
}

// 实时更新数据
watch(
  () => attrs.modelValue,
  newVal => {
    const type = attrs['columns-type'] ? attrs['columns-type'].join('-') : attrsDatePickerDefault['columns-type'].join('-')
    inputVal.value = newVal || ''
    currentDate.value = newVal ? newVal.split('-') : $day().format(formatTimeObj[type]).split('-')
  },
  { immediate: true }
)

// 清空时间
function clear() {
  emit('update:modelValue', '')
  emit('clear', '')
}

// 选中某一项后，点击确认按钮 { value: 前选中的时间 }
function confirm({ selectedValues }) {
  show.value = false
  const time = selectedValues.join('-')
  emit('update:modelValue', time)
  emit('confirm', time)
}
</script>
